﻿using System;
using System.IO;
using AvalonDock.Layout;
using BaseControlLibrary;
using QueryResource.Common;
using QueryResource.ViewModel;
using Microsoft.Win32;
using System.Windows;
using DBAccessLibrary.Common;
using SimpleControlLibrary.Common;
using SimpleControlLibrary.UI;

namespace SimpleControlLibrary.ViewModel
{
    public class MainViewModel : BasePropertyChange
    {
        readonly DBTreeViewModel _treeViewModel;
        private int _documentCount = 1;
        public MainViewModel(DBTreeViewModel treeview)
        {
            _treeViewModel = treeview;

            CreateDBCommand = new DelegateCommand(() =>
            {
                RegistDB regist = new RegistDB();
                if (regist.ShowDialog() == true)
                {
                    this._treeViewModel.Connection();
                }
            });

            TxtFormatCommand = new DelegateCommand(() =>
            {
                SQLControl control = GetActiveSqlControl();
                if (control != null)
                {
                    control.ViewModel.SqlFormatPainter(control.ViewModel.SelectText, true);
                }
            }, () =>
            {
                SQLControl control = ActiveSqlControl();
                if (control != null)
                {
                    return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                }
                return false;
            });

            FileOpenCommand = new DelegateCommand(() =>
            {
                OpenFileDialog dlg = new OpenFileDialog
                {
                    ValidateNames = true,
                    CheckPathExists = true,
                    CheckFileExists = true,
                    Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                };
                bool? showDialog = dlg.ShowDialog();
                if (showDialog != null && showDialog.Value)
                {
                    ShowNewWindowLoadFile(dlg.SafeFileName, dlg.FileName, true);
                }
            });
            FileSaveCommand = new DelegateCommand(() =>
            {
                SQLControl sqlcontrol;
                LayoutDocument panel = ActiveSqlControl(out sqlcontrol);
                if (sqlcontrol == null)
                {
                    return;
                }
                if (sqlcontrol.IsNewDocument)
                {
                    string fileName = string.Empty;
                    if (panel.Title.IndexOf('*') > 0)
                    {
                        fileName = panel.Title.Replace("*", "");
                    }
                    if (fileName != "文档")
                    {
                        fileName = "Temporary\\" + fileName;
                    }
                    sqlcontrol.SaveFile(fileName);
                    panel.Title = panel.Title.Replace("*", "");
                }
                else
                {
                    //文件
                    if (File.Exists(sqlcontrol.FilePath))
                    {
                        sqlcontrol.SaveFile(sqlcontrol.FilePath);
                        panel.Title = panel.Title.Replace("*", "");
                    }
                }
            }, () =>
            {
                SQLControl sqlcontrol;
                LayoutDocument panel = ActiveSqlControl(out sqlcontrol);
                if (sqlcontrol == null)
                {
                    return false;
                }
                if (panel.Title.IndexOf('*') < 0)
                    return false;
                return true;
            });
            FileSaveAsCommand = new DelegateCommand(() =>
            {
                SaveFileDialog dlg = new SaveFileDialog
                {
                    Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
                };
                bool? showDialog = dlg.ShowDialog();
                if (showDialog != null && showDialog.Value)
                {
                    SQLControl sqlcontrol;
                    LayoutDocument panel = ActiveSqlControl(out sqlcontrol);
                    if (sqlcontrol == null)
                    {
                        MessageBoxHelper.ShowCaption("没有可保存的数据", "提示");
                    }
                    else
                    {
                        sqlcontrol.SaveFile(dlg.FileName);
                        int index = panel.Title.IndexOf('*');
                        if (index > 0)
                        {
                            panel.Title = panel.Title.Remove(index);
                        }
                    }
                }

            }, () =>
            {
                SQLControl control = ActiveSqlControl();
                return control != null;

            });
            RunCommand = new DelegateCommand(() =>
            {
                SQLControl control = ActiveSqlControl();
                if (control != null)
                {
                    control.ViewModel.ExecSqlCommand.Execute(control.ViewModel.SelectText);
                }
            }, () =>
            {
                SQLControl control = ActiveSqlControl();
                if (control != null)
                {
                    return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                }
                return false;
            });
            ClearCommand = new DelegateCommand(() =>
            {
                SQLControl control = ActiveSqlControl();
                if (control != null)
                {
                    control.Clear();
                }
            }, () =>
            {
                SQLControl control = ActiveSqlControl();
                if (control != null)
                {
                    return !string.IsNullOrEmpty(control.ViewModel.SelectText);
                }
                return false;
            });
            FindCommand = new DelegateCommand(() => { });
            ReplaceCommand = new DelegateCommand(() => { });

            AddDocumentCommand = new DelegateCommand(() => ShowNewWindowLoadFile("新文档" + _documentCount++ +".txt", "", false));
        }

        #region 工具栏
        //新建数据源
        public void CreateDBExecuted()
        {
            RegistDB regist = new RegistDB();
            if (regist.ShowDialog() == true)
            {
                this._treeViewModel.Connection();
            }
        }
        //拷贝字段名
        public void CopyFieldNameExecuted()
        {
            this._treeViewModel.CopyCommand.Execute(this._treeViewModel.SelectedItem);
        }
        //格式刷
        public bool TxtFormatCanExecute()
        {
            SQLControl control = ActiveSqlControl();
            if (control != null)
            {
                return !string.IsNullOrEmpty(control.ViewModel.SelectText);
            }
            return false;
        }
        public void TxtFormatExecuted()
        {
            SQLControl control = ActiveSqlControl();
            if (control != null)
            {
                control.ViewModel.SqlFormatPainter(control.ViewModel.SelectText, true);
            }
        }
        //打开文件
        public void FileOpenExecuted()
        {
            OpenFileDialog dlg = new OpenFileDialog
            {
                ValidateNames = true,
                CheckPathExists = true,
                CheckFileExists = true,
                Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
            };
            bool? showDialog = dlg.ShowDialog();
            if (showDialog != null && showDialog.Value)
            {
                ShowNewWindowLoadFile(dlg.SafeFileName, dlg.FileName, true);
            }
        }

        //另存为文件
        public void FileSaveAsExecuted()
        {
            SaveFileDialog dlg = new SaveFileDialog
            {
                Filter = "文本文件 （*.txt)|*.txt|SQL 文件 (*.sql)|*.sql"
            };
            bool? showDialog = dlg.ShowDialog();
            if (showDialog != null && showDialog.Value)
            {
                SQLControl sqlcontrol;
                LayoutDocument panel = GetActiveSqlPanel(out sqlcontrol);
                if (sqlcontrol == null)
                {
                    MessageBoxHelper.ShowCaption("没有可保存的数据", "提示");
                }
                else
                {
                    sqlcontrol.SaveFile(dlg.FileName);
                    int index = panel.Title.IndexOf('*');
                    if (index > 0)
                    {
                        panel.Title = panel.Title.Remove(index);
                    }
                }
            }
        }
        public bool FileSaveAsCanExecute()
        {
            SQLControl control = GetActiveSqlControl();
            return control != null;
        }
        //运行
        public void RunSqlExecuted()
        {
            SQLControl control = ActiveSqlControl();
            if (control != null)
            {
                //先保存
                LayoutDocument dp = control.Tag as LayoutDocument;
                if (dp != null && dp.Title.IndexOf('*') > 0)
                {
                    string fileName = dp.Title.Replace("*", "");
                    if (fileName != "文档")
                    {
                        fileName = "Temporary\\" + fileName;
                    }
                    control.SaveFile(AppDomain.CurrentDomain.BaseDirectory + "\\" + fileName);
                    dp.Title = dp.Title.Replace("*", "");
                }
                //再执行
                control.ViewModel.ExecSqlCommand.Execute(control.ViewModel.SelectText);
            }
        }
        public bool RunSqlCanExecute()
        {
            SQLControl control = ActiveSqlControl();
            if (control != null)
            {
                return !string.IsNullOrEmpty(control.ViewModel.SelectText);
            }
            return false;
        }
        //皮肤
        public void SkinChanged(DependencyObject obj, string themeName)
        {
            //ThemeManager.ApplicationThemeName = themeName;
            //ThemeManager.SetThemeName(obj, themeName);
            //WriteTheme(themeName);
        }
        #endregion

        #region 命令
        public DelegateCommand CreateDBCommand { get; set; }
        public DelegateCommand TxtFormatCommand { get; set; }
        public DelegateCommand FileOpenCommand { get; set; }
        public DelegateCommand FileSaveCommand { get; set; }
        public DelegateCommand FileSaveAsCommand { get; set; }
        public DelegateCommand RunCommand { get; set; }
        public DelegateCommand ClearCommand { get; set; }
        public DelegateCommand FindCommand { get; set; }
        public DelegateCommand ReplaceCommand { get; set; }
        public DelegateCommand AddDocumentCommand { get; set; }
        #endregion

        public Func<SQLControl> GetActiveSqlControl { get; set; }
        public Action<string, string, bool> ShowNewWindowLoadFile { get; set; }
        public delegate LayoutDocument GetActiveSqlControlPanel(out SQLControl sqlcontrol);
        public event GetActiveSqlControlPanel GetActiveSqlPanel;

        private SQLControl ActiveSqlControl()
        {
            return GetActiveSqlControl();
        }
        public LayoutDocument ActiveSqlControl(out SQLControl sqlcontrol)
        {
            if (GetActiveSqlPanel != null)
            {
                return GetActiveSqlPanel(out sqlcontrol);
            }
            sqlcontrol = null;
            return null;
        }

    }
}
